package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.qmyx.admin.dao.OrdersDao;
import com.ytjj.qmyx.admin.dao.ProductBrandDao;
import com.ytjj.qmyx.admin.dao.ProductDao;
import com.ytjj.qmyx.admin.dao.ProductSpecDao;
import com.ytjj.qmyx.admin.dao.channel.FreightTemplateDao;
import com.ytjj.qmyx.admin.mapper.SupplyChainMsgMapper;
import com.ytjj.qmyx.admin.model.SupplyChainMsg;
import com.ytjj.qmyx.admin.model.SupplyChainMsgExample;
import com.ytjj.qmyx.admin.model.request.SupplyChainBrandRequest;
import com.ytjj.qmyx.admin.model.request.exportInterface.NotifyOrderInfoRequest;
import com.ytjj.qmyx.admin.model.request.goods.GoodsRequest;
import com.ytjj.qmyx.admin.model.request.goods.UpdateOrderExpressRequest;
import com.ytjj.qmyx.admin.model.request.goods.UpdateProductFreightRequest;
import com.ytjj.qmyx.admin.service.OrdersService;
import com.ytjj.qmyx.admin.service.ReceiveSupplyChainMsgService;
import com.ytjj.qmyx.admin.utils.ExpressDicUtil;
import com.ytjj.qmyx.mall.mapper.OrdersInfoMapper;
import com.ytjj.qmyx.mall.mapper.OrdersMapper;
import com.ytjj.qmyx.mall.mapper.ProductBrandMapper;
import com.ytjj.qmyx.mall.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReceiveSupplyChainMsgServiceImpl implements ReceiveSupplyChainMsgService {

    @Resource
    private SupplyChainMsgMapper supplyChainMsgMapper;
    @Autowired
    private OrdersService ordersService;
    @Resource
    private ProductSpecDao productSpecDao;
    @Resource
    private ProductDao productDao;
    @Resource
    private FreightTemplateDao freightTemplateDao;
    @Resource
    private OrdersDao ordersDao;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;


    /**
     * 通知销售渠道更新商品
     * @param type
     * @param msg
     * @param productId
     * @return void
     */
    @Override
    public void notifyProductUpdate(Integer type, String msg, Integer productId) {
        SupplyChainMsg record = new SupplyChainMsg();
        record.setType(type);
        record.setProductid(productId);
        record.setMsg(msg);
        supplyChainMsgMapper.insertSelective(record);
    }

    @Override
    public void notifyOrderUpdate(NotifyOrderInfoRequest request) {
        int count = ordersService.batchUpdateChildOrderStatus(request);
        Assert.isTrue(count>0,"更新渠道订单状态失败");
        ordersService.updateOrderStatus(request);
    }

    /**
     * 未读消息列表
     * @return
     */
    @Override
    public List<SupplyChainMsg> queryMsgList(Integer type) {
        SupplyChainMsgExample example = new SupplyChainMsgExample();
        example.createCriteria().andStatusEqualTo(type);
        List<SupplyChainMsg> list = supplyChainMsgMapper.selectByExample(example);
        return list;
    }

    /**
     * 设置已读
     * @param id
     * @return
     */
    @Override
    public SupplyChainMsg findById(Integer id) {
        SupplyChainMsg msg = supplyChainMsgMapper.selectByPrimaryKey(id);
        msg.setStatus(1);
        supplyChainMsgMapper.updateByPrimaryKeySelective(msg);
        return msg;
    }

    /**
     * 供应链新增品牌或者更新品牌时,更新销售端品牌
     * @param request
     */
    @Override
    public void addOrUpdateBrand(SupplyChainBrandRequest request) {
//        log.info("======供应链调用新增或修改渠道品牌====参数==={}",request);
//        List<ProductBrand> productBrands = productBrandDao.selectBySupplyBrandId(request.getId());
//        log.info("======供应链调用新增或修改渠道品牌====productBrands={}",productBrands);
//        //如果为空则新增,不为空则修改
//        if (CollectionUtils.isEmpty(productBrands)){
//            ProductBrand productBrand = new ProductBrand();
//            productBrand.setBrandName(request.getChineseName());
//            productBrand.setBrandLogo(request.getBrandLogo());
//            productBrand.setBrandBgimage(request.getBrandBanner());
//            productBrand.setBrandStory(request.getBrandDescr());
//            productBrand.setSupplyBrandId(request.getId());
//            productBrand.setIsShow(request.getIsShow());
//            List<Integer> countryId = productBrandDao.findCountryByChinaName(request.getCountry());
//            productBrand.setCountryInfoId(countryId.get(0));
//            int count = productBrandDao.insertSelective(productBrand);
//            log.info("======供应链调用新增渠道品牌======成功count>0={}",count);
//        }else {
//            List<ProductBrand> collect = productBrands.stream().filter(item -> item.getBrandName().equals(request.getOldChineseName())).collect(Collectors.toList());
//            if (!CollectionUtils.isEmpty(collect)){
//                ProductBrand productBrand = collect.get(0);
//                int count = 0;
//                if (2 == request.getBrandStatus()){
//                    count = productBrandMapper.deleteByPrimaryKey(productBrand.getId());
//                    productDao.updateBrandByBrandId(productBrand.getId());
//                }else {
//                    productBrand.setBrandName(request.getChineseName());
//                    productBrand.setBrandLogo(request.getBrandLogo());
//                    productBrand.setBrandBgimage(request.getBrandBanner());
//                    productBrand.setBrandStory(request.getBrandDescr());
//                    productBrand.setIsShow(request.getIsShow());
//                    List<Integer> countryId = productBrandDao.findCountryByChinaName(request.getCountry());
//                    productBrand.setCountryInfoId(countryId.get(0));
//                    count = productBrandMapper.updateByPrimaryKeySelective(productBrand);
////                    if (0 == request.getBrandStatus()){
////                        productDao.updateBrandByBrandId(productBrand.getId());
////                    }
//                }
//                log.info("======供应链调用修改渠道品牌======成功count>0={}",count);
//            }
//        }
    }
    @Override
    public void updateChannelProductSpecSupplyPrice(List<ProductSpec> request) {
        request.stream().forEach(item ->{
            log.info("===========供应链修改了供货价，要实时同步销售端==============供应链规格id:{},供货价:{}",item.getSupplyId(),item.getSupplyPrice());
            if (null != item.getSupplyId()){
                List<ProductSpec> productSpecList = productSpecDao.selectBySupId(item.getSupplyId());
                if (!CollectionUtils.isEmpty(productSpecList)){
                    productSpecDao.updateSupplyPriceBySupplyId(item.getSupplyId(),item.getSupplyPrice(),item.getCostPrice());
                }
            }
        });
    }

    @Override
    public void updateChannelProductCategory(GoodsRequest goodsRequest) {
        log.info("===========供应链修改商品分类，实时同步销售端==============供应链商品id:{},", goodsRequest.getSupplyProductId());
        if (null != goodsRequest.getSupplyProductId()) {
            List<Product> productList = productDao.selectBySupplyProductId(goodsRequest.getSupplyProductId());
            if (!CollectionUtils.isEmpty(productList)) {
                productDao.updateCategoryBySupplyProductId(goodsRequest.getSupplyProductId(), goodsRequest.getTopCategoryId(), goodsRequest.getCategoryId(), goodsRequest.getBottomCategoryId());
            }
        }
    }

    @Override
    public int updateOrderExpress(UpdateOrderExpressRequest request) {
        log.info("====供应链触发更新订单快递单号====={}", JSONObject.toJSON(request));
        if (request.getUpdateOrderFlag().equals(1) && !StringUtils.isEmpty(request.getChildOrderNo())) {
            return ordersService.updateOrderExpressBySaleSystem(request.getChildOrderNo(), request.getExpressCode(), request.getExpressNo());
        } else if  (request.getUpdateOrderFlag().equals(0) && !StringUtils.isEmpty(request.getChildOrderNo()) ) {
            OrdersInfo ordersInfo = ordersService.queryByChildOrderNo(request.getChildOrderNo());
            String orderinfoStatus = ordersInfo.getOrderinfoStatus();
            if (null != request.getOrderInfoStatus() && !String.valueOf(request.getOrderInfoStatus()).equals(ordersInfo.getOrderinfoStatus())) {
                ordersInfo.setOrderinfoStatus(request.getOrderInfoStatus().toString());
            }
            if (org.apache.commons.lang.StringUtils.isNotBlank(request.getExpressNo()) && !request.getExpressNo().equals(ordersInfo.getExpressNo())) {
                ordersInfo.setExpressNo(request.getExpressNo());
                ordersInfo.setDeliveryTime(request.getImportTime());
            }
            if (org.apache.commons.lang.StringUtils.isNotBlank(request.getExpressCode()) && !request.getExpressCode().equals(ordersInfo.getExpressCompanyNo())) {
                ordersInfo.setExpressCompanyNo(request.getExpressCode());
            }

            ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
            //修改主订单状态
            List<OrdersInfo> ordersInfos = ordersDao.getAllOrdersInfoByOrderId(ordersInfo.getOrderId());
            if (!CollectionUtils.isEmpty(ordersInfos)) {
                int index = 0;
                for (OrdersInfo info : ordersInfos) {
                    if (info.getOrderinfoStatus().equals(ordersInfo.getOrderinfoStatus())) {
                        index += 1;
                    }
                }
                if (index == ordersInfos.size()) {
                    Orders order = new Orders();
                    order.setOrderStatus(ordersInfo.getOrderinfoStatus());
                    OrdersExample ordersExample = new OrdersExample();
                    ordersExample.createCriteria()
                            .andIdEqualTo(ordersInfo.getOrderId());
                    ordersMapper.updateByExampleSelective(order, ordersExample);
                }
            }
            Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
            log.info("订单之前状态orderinfoStatus:{}",orderinfoStatus);
            if ("1".equals(orderinfoStatus) && request.getOrderInfoStatus()==2) {
                sendDeliverySms(orders,ordersInfo,ordersInfos.size());
            }
        }
        return 0;
    }

    private void sendDeliverySms(Orders orders, OrdersInfo ordersInfo, int size) {
        log.info("开始发送发货短信");
        // 发送短信
        try {
            String productName = ordersInfo.getProductName();
            if (size > 1) {
                if (productName.length() > 12) {
                    productName = productName.substring(0, 12) + "等";
                } else {
                    productName = productName + "等";
                }
            } else {
                if (productName.length() > 12) {
                    productName = productName.substring(0, 12) + "等";
                }
            }

            String expressCompany = ExpressDicUtil.getKey(ordersInfo.getExpressCompanyNo());

            log.info("===订单：{}已发货，接收短信手机号{}，发送到MQ===",orders.getOrderNo(),orders.getUserPhone());
            SmsDto smsDto = new SmsDto();
            smsDto.setPhone(orders.getUserPhone());
            smsDto.setType(6);
            smsDto.setCode(productName);
            smsDto.setExpressNo(ordersInfo.getExpressNo());
            smsDto.setExpressCompany(expressCompany);
            smsDto.setOrderSource(orders.getOrderSource());
            smsDto.setChannel(orders.getChannel());
            smsDto.setDomainUrl(orders.getDomainUrl());
            rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, smsDto);

        } catch (Exception e) {
            log.error("供应链发货触发更新订单快递定点杆信息发送短信失败,{}",e);
        }
    }
}
